package com.chatdating.controller;


import com.chatdating.entity.ChatSessionUser;
import com.chatdating.entity.Member;
import com.chatdating.entity.Session;
import com.chatdating.entity.User;
import com.chatdating.entity.dto.LoginDto;
import com.chatdating.entity.dto.RegisterDto;
import com.chatdating.entity.pojo.ChatMessages;
import com.chatdating.entity.pojo.Result;
import com.chatdating.entity.pojo.TockenUserInfo;
import com.chatdating.mapper.ChatMessageMapper;
import com.chatdating.mapper.MemberMapper;
import com.chatdating.mapper.UserMapper;
import com.chatdating.redis.RedisComponet;
import com.chatdating.entity.vo.LoginInVo;
import com.chatdating.service.AuthService;
import com.chatdating.service.SessionService;
import com.chatdating.service.UserService;
import com.chatdating.utils.EmptyUtil;
import com.chatdating.utils.SHA256Util;

import org.apache.logging.log4j.message.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.time.ZoneId;

@RestController
@RequestMapping("/user")
public class AuthController {

    private static final Logger logger = LoggerFactory.getLogger(AuthController.class);

    @Autowired
    private AuthService authService;
    @Autowired
    private UserService userService;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private ChatMessageMapper chatMessageMapper;


    @Autowired
    private SessionService sessionService;
    @Autowired
    private UserMapper userMapper;

    /**
     *   用户注册
     */
    @PostMapping(value = "/register")
    @Transactional
    public Result register(@RequestBody RegisterDto user) {
        if (EmptyUtil.isNotEmpty(userService.findByNmme(user.getUsername()))) {
            return Result.error(400, "用户名已存在");
        }
        User user1 = new User();
        try {
            user1.setAddress(user.getAddress());
            user1.setPassword(user.getPassword());
            user1.setUsername(user.getUsername());
            user1.setAge(user.getAge());
            user1.setHead( user.getHead());
            user1.setGender( user.getGender());
            user1.setRealname(user.getRealname());
            user1.setBackground(user.getXuexinPhoto());
            user1.setIdcard( user.getIdCardPhoto());
            user1.setPhone(user.getPhone());
            user1.setLoginTime(Long.valueOf(0));
            user1.setLastTime( Long.valueOf(0));

            Integer save = userService.save(user1);

            if(save == 1){

                //注册成功 统一为用户添加一条会话消息  （提示  恭喜您已经注册成功 请等待后台验证）
                //1  保存会话记录
                Session session = new Session();
                 session.setLastTime(String.valueOf(System.currentTimeMillis()));
                 session.setLastMessage("恭喜您已经注册成功 请等待后台验证");
                 //添加之后返回主键值
                Integer save1 = sessionService.save(session);
                // 2 保存会话联系人记录
                ChatSessionUser chatSessionUser = new ChatSessionUser();
                chatSessionUser.setSessionId(session.getSessionId().toString());
                chatSessionUser.setContactId(String.valueOf(1));
                chatSessionUser.setContentHead(null);
                chatSessionUser.setUserId(user.getUsername());
                chatSessionUser.setContentName("官方");
                 sessionService.isnert(chatSessionUser);
                 //添加消息列表
                ChatMessages chatMessages = new ChatMessages();
                chatMessages.setSessionId(session.getSessionId());
                chatMessages.setMessageContent("恭喜您已经注册成功 请等待后台验证");
                chatMessages.setSendUserId(String.valueOf(1));
                chatMessages.setSendUserNickName("官方");
                chatMessages.setSendTime(System.currentTimeMillis());
                chatMessages.setContactId(String.valueOf(user1.getId()));
                chatMessages.setStatus(1);
           chatMessageMapper.insert(chatMessages);
                return Result.success("注册成功");
            }else{
                return Result.error(500, "注册失败，请稍后重试");
            }
        } catch (Exception e) {
            logger.error("注册失败: {}", e.getMessage());
            return Result.error(500, "注册失败，请稍后重试");
        }
    }

    /**
     * 用户登录
     *
     */

    @Transactional
    @PostMapping("/login")
    public Result login(@RequestBody LoginDto loginDto){

        if(EmptyUtil.isEmpty(loginDto)||EmptyUtil.isEmpty(loginDto.getName())||EmptyUtil.isEmpty(loginDto.getPassword())){
            return Result.error(400,"用户名或密码为空");
        }
        User user = userService.findByNmme(loginDto.getName());
        int userId = user.getId();
        String hash = user.getPassword();  //原来的 password
        String input = loginDto.getPassword();
        boolean verify = SHA256Util.verify(input,hash);
       if(!verify){
       return Result.error(400,"密码错误");
       }

        LoginInVo loginInVo = new LoginInVo();

        String tocken = authService.authenticate(loginDto.getName());
        loginInVo.setUsername(user.getUsername());
        loginInVo.setAvatar(user.getHead());
        loginInVo.setTocken(tocken);
        loginInVo.setUserid(Long.valueOf(userId));

        Member byUid = memberMapper.getByUid(userId);
        if(EmptyUtil.isEmpty(byUid)){
            loginInVo.setIsvip("0");
        }else {
            ZoneId zone = ZoneId.of("Asia/Shanghai"); // 或 ZoneOffset.UTC
            loginInVo.setVipExpireTime(byUid.getEndTime().atZone(zone).toInstant().toEpochMilli());
            loginInVo.setIsvip("1");
        }

        return Result.success(loginInVo);
    }



}
